import sqlite3
import database.sql as Sql

class Database:
    filename = None
    connect = None

    def init(self, name):
        self.filename = name
        self.connect = sqlite3.connect(self.filename, check_same_thread=False)

    def select(self, sql: str):
        self.connect.row_factory = self.dictFactory
        cur = self.connect.cursor()
        queryResult = cur.execute(sql).fetchall()
        return queryResult

    def insert(self, sql: str, ifLog):
        if ifLog is True:
            print("执行的sql语句为\n{}".format(sql))
        self.connect.cursor().execute(sql)
        self.connect.commit()

    def update(self, sql: str):
        self.connect.cursor().execute(sql)
        self.connect.commit()

    def delete(self, sql: str):
        self.connect.cursor().execute(sql)
        self.connect.commit()

    def CloseDB(self):
        self.connect.cursor().close()
        self.connect.close()

    def dictFactory(self, cursor, row):
        d = {}
        for index, col in enumerate(cursor.description):
            d[col[0]] = row[index]
        return d

    def dbop(self,sql):
        self.connect.cursor().execute(sql)
        self.connect.commit()

    def vacuum(self):
        sql = Sql.vacuum
        self.dbop(sql)